<template>
  <div class="roleEdit addButton">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>组织管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/authority/role/list' }">角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色权限编辑</el-breadcrumb-item>
    </el-breadcrumb>
    <div class="form">
      <el-form ref="form" :model="form" label-width="100px" size="small" :rules="rules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" style="width:230px" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="权限选择">
          <el-tree
            style="width:50%"
            :data="treeData"
            :default-checked-keys='defaultChecked'
            :default-expanded-keys="defaultChecked"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps">
          </el-tree>
        </el-form-item>
        <el-form-item>
          <el-button style="background:#fb9654;color:#fff" @click="onSubmit">确认修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  mounted() {
    this.roleId = this.$route.query.id;
    this.form.roleName = decodeURIComponent(String(this.$route.query.name));
    this.getRolePermissionList();
  },
  data() {
    const validateName = (rule, value, callback) => {
      console.log(value, "123123");
      if (value == null) {
        callback(new Error("角色名称不能为空！"));
      } else if (value.replace(/(^\s*)|(\s*$)/g, "") === "") {
        callback(new Error("请输入正确的角色名称！"));
      } else {
        callback();
      }
    };
    return {
      roleId: "", // 角色id
      treeData: [],
      defaultChecked: [],
      defaultProps: {
        children: "childrenPermission",
        label: "menuName"
      },
      form: {
        roleName: "" // 角色名称
      },
      rules: {
        roleName: [
          { required: true, trigger: "change", validator: validateName }
        ],
      },
    };
  },
  methods: {
    getRolePermissionList() {
      this.$api.authority.getRolePermissionList({ id: this.roleId })
        .then((res) => {
          console.log(res);
          this.treeData = this.setDefaultChecked(res.data);
          // console.log("defaultChecked:",)
        });
    },
    /**
     *
     * @param treeData 递归数据
     * @param parentId 递归数据的父id，第一次进来时为0
     * @returns {*}
     */
    setDefaultChecked(treeData,parentId="") {
      for (let index in treeData) {
        //是三级权限但默认选中的添加到默认勾选的数组中
        if (treeData[index].isItSelected === 1) {
          treeData[index].isItSelected = true;
          this.defaultChecked.push(treeData[index].id);
        } else {
          // 如果存在子菜单为未选中 如果有父id 则把父id设置为未选中
          treeData[index].isItSelected = false;
          if(parentId){
            let index = this.defaultChecked.findIndex(id=>id===parentId);
            this.defaultChecked.splice(index,1);
          }
        }
        // 递归调用
        if (treeData[index].childrenPermission) {
          this.setDefaultChecked(treeData[index].childrenPermission,treeData[index].id);
        }
      }
      return treeData;
    },
    onSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let permissionIds = this.$refs.tree.getCheckedKeys();
          let params = {
            roleId: this.roleId,
            permissionIds: permissionIds.join(","),
          };
          this.$api.authority.rolePermissionUpdate(params)
          .then((res)=>{
             if(res.code===200){
               this.$message.success("修改成功");
               this.$router.back();
             }
          })
        } else {
          this.$message.success("修改失败");
          console.log("error submit!!");
          return false;
        }
      });
    },
  }
};
</script>
<style scoped>
@import url('./edit.css');
</style>
